import { Component, OnInit } from "@angular/core";
import { CesiumMap } from "src/app/cesium-map/utils/cesiumMap";
import { InitCesiumService } from "src/app/cesium-map/services/InitCesiumService";
import { BASE_URL } from "src/app/config/global-const";
import { LAYER_SERVICE } from "src/app/config/project.config";
import * as $ from 'jquery'
declare var Cesium;
@Component({
  selector: "app-case1",
  templateUrl: "./case1.component.html",
  styleUrls: ["./case1.component.less"],
})
export class Case1Component implements OnInit {
  cesiumMap: CesiumMap;
  Viewer: any;
  params;
  lanTianOSGB;

  list: any = [
    {
      id: 0,
      title: 'arcgis地图',
      server: 'ArcGisMapServerImageryProvider',
      par: {
        name: "img_arcgis",
        url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
      }
    },
    {
      id: 1,
      title: 'bing地图',
      par: {
        key: 'Av63hPkCmH18oGGn5Qg3QhLBJvknZ97xbhyw3utDLRtFv7anHjXNOUQbyWBL5fK5',
        url: "//dev.virtualearth.net"
      },
      server: 'BingMapsImageryProvider'
    },
    {
      id: 2,
      title: '高德影像',
      par: {
        url: "http://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}"
      },
      server: 'UrlTemplateImageryProvider'
    },
    {
      id: 3,
      title: '高德矢量',
      par: {
        url: "http://webst02.is.autonavi.com/appmaptile?style=7&x={x}&y={y}&z={z}"
      },
      server: 'UrlTemplateImageryProvider'
    },
    {
      id: 4,
      title: '天地地图',
      par: [
        {
          url: "http://t0.tianditu.com/img_w/wmts?tk=6ac4858482f0852842116eee4ff0574c",
          layer:'img',
          style:'default',
          tileMatrixSetID:'w',
          format:'tiles',
          maximumLevel: 18
      },
      {
        url: 'http://t0.tianditu.gov.cn/cia_w/wmts?tk=6ac4858482f0852842116eee4ff0574c',
        layer:'cia',
        style:'default',
        tileMatrixSetID:'w',
        format:'tiles',
        maximumLevel: 18
      },
      ],
      server: 'WebMapTileServiceImageryProvider'
    },
  ]

  selectedValue: any = null

  constructor(private InitCesiumService: InitCesiumService) {}

  ngOnInit() {
    this.cesiumMap = new CesiumMap();
  }

  mapCreate($event) {
    this.Viewer = $event;
    this.Viewer.terrainProvider = this.cesiumMap.CesiumTerrainProvider({
      url: "/files/dixingtu/fengkaiData", // 地址记得换成自己的地形数据地址
      requestWaterMask: false, // 开启法向量
      requestVertexNormals: false, // 开启水面特效
    });
    this.set3DTileset();
    this.addMask()
    this.setMouse()
  }
    /**
   * 鼠标事件
   */
     setMouse() {
      let handler = new Cesium.ScreenSpaceEventHandler(this.Viewer.scene.canvas)
      let leftclick = Cesium.ScreenSpaceEventType.LEFT_CLICK;
      handler.removeInputAction(leftclick);
      handler.setInputAction((e) => {
        let pickObj = this.Viewer.scene.pick(e.position);
        if (Cesium.defined(pickObj)) {
          if (pickObj.id && pickObj.id instanceof Cesium.Entity) {//点击entity
            this.setCenter()
          }
          return
        }
      }, leftclick)
    }
  

  /**
   * 添加行政区划
   */

  addMask(){
    let url = `${BASE_URL}/geoserver/wfs?service=wfs&version=2.0.0&request=GetFeature&typeNames=${LAYER_SERVICE}:t_region&srsname=EPSG:4326&outputFormat=application/json&cql_filter=rpno=441225`
    $.get(
      url,
      (data) => {
        this.addExtrudedGeoJson(this.Viewer, data)
      }
    )
  }
  addExtrudedGeoJson(viewer, url) {
    const promise = new Cesium.GeoJsonDataSource.load(url);
    promise.then((datasource) => {
      viewer.dataSources.add(datasource);   // 加载这个geojson资源 
      const entities = datasource.entities.values;
      var colorHash = {};
      for (let index = 0; index < entities.length; index++) {
        const entity = entities[index];
        entity.polygon.heightReference = 5000;  // 贴地
        entity.polygon.height = 2000;  // 距地高度0米
        // entity.polygon.extrudedHeightReference = 1000; //拉伸
        // entity.polygon.extrudedHeight = 1000; // 拉伸高度

        var name = entity.name;  //geojson里面必须得有一个name属性，entity.name对应
        var color = colorHash[name]; //可以使两个同名要素使用同一种颜色。。。
        if (!color) {
          color = Cesium.Color.fromRandom({
            alpha: 0.8
          });
          colorHash[name] = color;
        }
        // entity.polygon.material = color;
        entity.polygon.outline = false;
        entity.polygon.extrudedHeight = Math.floor(Math.random() * 2000 + 1000) //20000~60000的随机数，单位是米
      }
      viewer.flyTo(datasource);

    });

  }
  set3DTileset() {
    var tileset1 = new Cesium.Cesium3DTileset({
      url: "/files/dixingtu/fengkai-tileset/tileset.json",
      // show:false
    });
    tileset1.readyPromise
      .then((tileset) => {
        this.Viewer.scene.primitives.add(tileset);
        this.lanTianOSGB = tileset;
        this.adjustHeight(20);
        // this.Viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(0.0, -0.5, tileset.boundingSphere.radius * 2.0));
      })
      .catch(function (error) {
        console.log(error);
      });
  }
/**
 * 
 * @param height 
 */
  adjustHeight(height) {
    var cartographic = Cesium.Cartographic.fromCartesian(
      this.lanTianOSGB.boundingSphere.center
    );
    var surface = Cesium.Cartesian3.fromRadians(
      cartographic.longitude,
      cartographic.latitude,
      0.0
    );
    var offset = Cesium.Cartesian3.fromRadians(
      cartographic.longitude,
      cartographic.latitude,
      height
    );
    var translation = Cesium.Cartesian3.subtract(
      offset,
      surface,
      new Cesium.Cartesian3()
    );
    this.lanTianOSGB.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
  }

  /**
   * 回到视野
   */
   setCenter() {
    console.log(211);
    this.Viewer.camera.flyTo({
      // fromDegrees()方法，将经纬度和高程转换为世界坐标
      destination: Cesium.Cartesian3.fromDegrees(
        111.60829020123631,
        23.453477687796436,
        1000
      ),
      orientation: {
        heading: 6, //代表镜头左右方向,正值为右,负值为左,360度和0度是一样的
        // 视角
        pitch: -0.3187528970141864, //俯视角，默认-90，垂直向下
        roll: 0, // 旋转角
      },
      duration: 5,
    });
    setTimeout(() => {
      let len = this.Viewer.dataSources.length;
      if (len > 0) {
        for (let i = 0; i < len; i++) {
          var dataSource = this.Viewer.dataSources.get(i);
          this.Viewer.dataSources.remove(dataSource);
        }
      }
    }, 1000)
  }

  
  gohome() {
    let len = this.Viewer.dataSources.length;
    if (len > 0) {
      for (let i = 0; i < len; i++) {
        var dataSource = this.Viewer.dataSources.get(i);
        this.Viewer.dataSources.remove(dataSource);
      }
    }
    this.addMask()
  }

    /**
   * 底图切换
   */
     layerCut() {
      let layerPar: any={}
      this.list.forEach(element => {
        if (this.selectedValue == element.id) {
          layerPar =element
        }
      })
      if(this.selectedValue!=4){
        var img = new Cesium[`${layerPar['server']}`]({
          ...layerPar.par
        });
        this.addlayer(img)
      }else{
        layerPar.par.forEach(item=>{
          var img = new Cesium[`${layerPar['server']}`]({
            ...item
          });
          this.addlayer(img)
        })
  
      }
      
  
    }
  
    addlayer(img){
      var layers = this.Viewer.scene.imageryLayers;
      layers.addImageryProvider(img);
    }
}
